package org.saxion.saktiehuis.service;

import java.util.List;

import org.saxion.saktiehuis.dao.GenericDao;
import org.saxion.saktiehuis.model.User;
import org.saxion.saktiehuis.tools.PasswordHasher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class UserService {
	@Autowired
	private GenericDao<User, Integer> userDao;

	public UserService() {
		super();
	}

	public User getUserByName(String username) {
		List<User> list = userDao.findAllByProperty("name", username);
		return (!list.isEmpty()) ? list.get(0) : null;
	}

	public boolean login(String username, String password) {
		List<User> users = userDao.findAllByProperty("name", username);
		if (!users.isEmpty()) {
			String wantedPass = users.get(0).getPassword();
			String inputPass = PasswordHasher.hashPassword(password);
			if (inputPass.equals(wantedPass))
				return true;
		}
		return false;
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public boolean register(String username, String password) {
		String hashedPassword = PasswordHasher.hashPassword(password);
		User u = new User(username, hashedPassword);
		return (userDao.save(u) != null) ? true : false;
	}

}
